package vn.com.fsoft.model.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;


import vn.com.fsoft.model.dao.IAddressDAO;
import vn.com.fsoft.model.entities.AddressNew;
import vn.com.fsoft.utility.HibernateUtils;

public class AddressDAO extends HibernateUtils implements IAddressDAO {
	
	private Session session;
	public AddressDAO(){
		if(session == null)
			session = getSessionFactory().openSession();
	}
	private static int totalPage;
	public List<AddressNew> lookUpAddress(String postCode, String street,
			String townName,int pageSize, int currentPage) {
		try {
			if(postCode == null || street == null || townName == null) {
				return null;
			}
			session.getTransaction().begin();
			String sql = "select new vn.com.fsoft.model.entities.AddressNew(" +
					"a.addressId,a.addressDetail,a.postCode," +
					"t.townName,c.countryName,cty.countyName,a.street)" +
					" from Country c " +
					"inner join c.county cty " +
					"inner join cty.towns t " +
					"inner join t.listAddress a where 1=1 ";
			if(postCode.length()>0)
				sql+=" and lower(a.postCode) like :pCode";
			if(street.length()>0)
				sql+=" and lower(a.street) like :street";
			if(townName.length()>0)
				sql+=" and lower(t.townName) like :townName";
			
			Query query = session.createQuery(sql);
			if(postCode.length()>0){
				postCode = "%"+postCode.toLowerCase()+"%";
				query.setParameter("pCode", postCode);
			}
			if(street.length()>0){
				street = "%"+street.toLowerCase()+"%";
				query.setParameter("street", street);
			}
			if(townName.length()>0){
				townName = "%"+townName.toLowerCase()+"%";
				query.setParameter("townName", townName);
			}
			//count(*)
			int totalRecord = query.list().size();		
			setTotalPage(totalRecord,pageSize);			
			query.setFirstResult(pageSize * (currentPage - 1));
			query.setMaxResults(pageSize);			
			List<AddressNew> list = query.list();
			session.flush();
			session.getTransaction().commit();
			session.close();
			return list;
		} catch (Exception e) {
			session.getTransaction().rollback();
		}
		return null;
	}
	@Override
	public int getTotalPage() {
		return totalPage;
	}
	public void setTotalPage(int totalRecord,int pageSize) {
		int totalPage = 0;
		if(totalRecord%pageSize==0){
			totalPage = totalRecord/pageSize;
		} else {
			totalPage = totalRecord/pageSize + 1;
		}
		AddressDAO.totalPage = totalPage;
	}	
}
